import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

//引入路由
import router from './routers/index';

//引入Vant组件库
import Vant from 'vant';
//引入所有组件的基本样式
import 'vant/lib/index.css';

//引入封装的请求
import Http from '@/services/request';

//引入工具函数
import Utils from '@/utils/utils';

//引入状态管理
import { createPinia } from 'pinia';

//引入管理持久化插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

import vue3Cookies from 'vue3-cookies';

const app = createApp(App)
    .use(router)
    .use(Vant)
    .use(Http)
    .use(createPinia().use(piniaPluginPersistedstate))
    .use(Utils)
    .use(vue3Cookies)
    .mount('#app');

// 全局前置路由守卫
router.beforeEach(async (to, from) => {
    const isLogin = to?.meta?.isLogin === true ? true : false;

    if (isLogin === true) {
        // 获取用户登录信息
        const business = app.$business;

        if (!business.value || Object.getOwnPropertyNames(business.value).length === 0) {
            app.$fail('请先登录');

            return { path: '/business/login' }
        }

        const id = business.value.id ?? 0;
        const mobile = business.value.mobile ?? '';

        const params = {
            id,
            mobile
        }

        const result = await app.$http.post('/business/check', params);

        if (result.code === 1) {
            app.$business.value = result.data;

            // 放行
            return true;
        } else {
            app.$business.value = {};

            app.$fail(result.msg);

            return { path: '/business/login' }
        }
    }
});